namespace Maple.Branch.Permissions.EfCoreConfigurations
{
    using System;
    using Consts;
    using Entities;
    using JetBrains.Annotations;
    using Microsoft.EntityFrameworkCore;
    using Options;
    using Volo.Abp;
    using Volo.Abp.EntityFrameworkCore.Modeling;

    public static class PermissionsModelBuilderExtensions
    {
        public static void ConfigurePermissions(
            [NotNull] this ModelBuilder builder,
            [CanBeNull] Action<PermissionsModelBuilderOption> optionsAction = null)
        {
            Check.NotNull(builder, nameof(builder));

            var options = new PermissionsModelBuilderOption(
                ModuleDbOptions.Prefix,
                ModuleDbOptions.Schema
            );

            optionsAction?.Invoke(options);

            builder.Entity<PermissionGrant>(b =>
            {
                b.ToTable(options.TablePrefix + nameof(PermissionGrant), options.Schema);

                b.ConfigureByConvention();

                b.Property(x => x.Name).HasMaxLength(PermissionGrantConsts.MaxNameLength).IsRequired();
                b.Property(x => x.ProviderName).HasMaxLength(PermissionGrantConsts.MaxProviderNameLength).IsRequired();
                b.Property(x => x.ProviderKey).HasMaxLength(PermissionGrantConsts.MaxProviderKeyLength).IsRequired();

                b.HasIndex(x => new { x.Name, x.ProviderName, x.ProviderKey });
            });
        }
    }
}
